package com.hontech.bv.conn

import android.util.Log
import android.util.SparseArray
import kotlinx.coroutines.CompletableDeferred

class Router {

    private val contain = SparseArray< CompletableDeferred<ReadFrame> >()

    fun set(frame: WriteFrame): CompletableDeferred<ReadFrame> {
        val promise = CompletableDeferred<ReadFrame>()
        synchronized(this) {
            contain.set(frame.promiseIndex(), promise)
        }
        return promise
    }

    fun notify(frame: ReadFrame) {
        var promise: CompletableDeferred<ReadFrame>?
        synchronized(this) {
            promise = contain.get(frame.promiseIndex())
            contain.delete(frame.promiseIndex())
        }
        if (promise == null) {
            Log.e("异常", "promise 没有 $frame")
            return
        }
        promise!!.complete(frame)
    }

    fun delete(frame: WriteFrame) {
        synchronized(this) {
            contain.delete(frame.promiseIndex())
        }
    }

    fun reset() {
        synchronized(this) {
            contain.clear()
        }
    }

}


